//index.js
const app = getApp()
 
Page({
  data: {
    isShow:false,
    isImg:false,
    isResult:true,
    isSao:false,
    isWenzi:false,
    isLog:false,
    isCha:true,
    isChongxin:true,
    isDonghua:false,
    selImg:"",
    saoyisao:1,
    beauty:"",
    gender:"",
    age:"",
    expression:"",
    biaoqing:["面无表情","皮笑肉不笑","微笑脸","笑容灿烂","狂笑"]
  },
  //授权
  getUserInfo(res) {
    console.log(res);
    wx.setStorage({
      key: 'isLog',
      data: 'true',
    })
    app.globalData.user = res.detail.userInfo;
    this.setData({
      isLog:true
    })

    //删除旧的用户登录信息
    let date = new Date();
    let time =  date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
    wx.cloud.callFunction({
      name:"getUserInfoTime",
      success(res){
        console.log(11111,res);
        for(var i=0;i<res.result.res.data.length;i++){
          if(time != res.result.res.data[i].time){
            wx.cloud.callFunction({
              name:"deleteUserInfo",
              data:{
                id:res.result.res.data[i]._id,
                time:res.result.res.data[i].time
              },
              success(res){
                console.log(res);
              },
              fail(err){
                console.log(err);
              }
            })
          }
        }
      },
      fail(err){
        console.log(err);
      }
    })

    //保存用户信息
    wx.cloud.callFunction({
      name:"setUserInfo",
      data:{
        name:app.globalData.user.nickName
      },
      success(res){
        console.log(res);
      },
      fail(err){
        console.log(err);
      }
    })
  },
  //扫一扫按钮功能
  getPhoto(){
    var that = this;
    //切换到获取图片
    if(this.data.saoyisao==1){
      this.setData({
        isShow: true,
      })
    }else if(this.data.saoyisao==2){
      //检查用户玩的次数
      wx.cloud.callFunction({
        name:"getUserInfoTime",
        success(res){
          console.log(res);
          if(res.result.res.data[0].gameCount < 10){
            //更改用户玩的次数
            wx.cloud.callFunction({
              name:"getUserInfoTime",
              success(res){
                console.log(res);
                var gameCount = ++res.result.res.data[0].gameCount;
                wx.cloud.callFunction({
                  name:"updateUserInfo",
                  data:{
                    id:res.result.res.data[0]._id,
                    gameCount:gameCount,
                    prizeCount:res.result.res.data[0].prizeCount
                  },
                  success(res){
                    console.log(res);
                  },
                  fail(err){
                    console.log(err);
                  }
                })
              },
              fail(err){
                console.log(err);
              }
            })

            //检测图片
            that.setData({
              saoyisao:4,
              isDonghua:true
            })
            wx.showToast({
              title: '检测中',
              icon: "loading",
              duration:5000
            })
            that.base64(that.data.selImg).then(res=>{
              // console.log(res);
              return that.faceDetection(res)
            }).then(res=>{
              wx.showToast({
                title: '检测成功',
                icon: "success",
              })
              console.log(res);
              let exp = res.result.res.FaceInfos[0].FaceAttributesInfo.Expression;
              let num;
              if (exp==0){
                num = 0;
              }else if(40>=exp&&exp>0){
                num = 1;
              } else if (60 >= exp && exp>40){
                num = 2;
              } else if (100 >= exp && exp>60){
                num = 3;
              }else if(exp==100){
                num = 4;
              }
              that.setData({
                isChongxin:true,
                isDonghua: false,
                beauty: res.result.res.FaceInfos[0].FaceAttributesInfo.Beauty,
                age: res.result.res.FaceInfos[0].FaceAttributesInfo.Age,
                expression:that.data.biaoqing[num],
                gender: res.result.res.FaceInfos[0].FaceAttributesInfo.Gender==0?"女":"男",
                isSao:true,
                isResult:false,
                isCha:false,
                isWenzi:true
              })
            },err=>{
              wx.showToast({
                title: '照片解析失败，请重新上传',
                icon:"none"
              })
            })
          }else{
            wx.showToast({
              title:"您玩的次数今天已达到限制，期待您明天的参与",
              icon:"none",
              duration:3000
            })
            setTimeout(function(){
              wx.navigateTo({
                url:"../index/index"
              })
            },3000)
          }
        },
        fail(err){
          console.log(err);
        }
      })
    }
  },
  //跳转到result
  toYouka(){
    wx.navigateTo({
      url: '/pages/result/result?beauty='+this.data.beauty
    })
  },
  //选择本机自拍照
  selImg(){
    console.log(1);
    let that = this;
    wx.chooseImage({
      sourceType: ["album"],
      success: function(res) {
        console.log(res);
        that.setData({
          selImg:res.tempFilePaths[0],
          isImg:true,
          saoyisao: 2,
          isChongxin:false
        })
      },
    })
  },
  //相机拍照
  takePhoto(){
    let that = this;
    wx.chooseImage({
      sourceType: ["camera"],
      success: function(res) {
        console.log(res);
        that.setData({
          selImg:res.tempFilePaths[0],
          isImg:true,
          isChongxin: false
        })
      },
    })
  },
  chongxinxuanze(){
    this.setData({
      isChongxin:true,
      isImg:false,
      selImg:""
    })
  },
  //图片转为base64格式
  base64(imgPath) {
    const fs = wx.getFileSystemManager();
    return new Promise((resolve, reject) => {
      fs.readFile({
        filePath: imgPath,
        encoding: "base64",
        success(res) {
          console.log(res)
          resolve(res.data);
        },
        fail() {

        }
      })
    })
  },
  //调用人脸识别接口
  faceDetection(base64Img){
    return new Promise((resolve,reject)=>{
      wx.cloud.callFunction({
        name: "faceDetect",
        data: {
          base64Img
        },
        success:(res)=> {
          console.log(res)
          resolve(res)
        },
        fail:(err)=> {
          reject(err);
        }
      })
    })
  },
  onLoad: function() {
    let that = this;
    wx.getStorage({
      key: 'isLog',
      success: function(res) {
        console.log(res)
        that.setData({
          isLog:res.data
        })
      },
    })
    
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })


              console.log(3333,this.data.userInfo);
              //删除旧的用户登录信息
              let date = new Date();
              let time =  date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
              wx.cloud.callFunction({
                name:"getUserInfoTime",
                success(res){
                  console.log(22222,res);
                    if(time != res.result.res.data[0].time){
                      wx.cloud.callFunction({
                        name:"deleteUserInfo",
                        data:{
                          id:res.result.res.data[0]._id,
                          time:res.result.res.data[0].time
                        },
                        success(res){
                          console.log(res);
                        },
                        fail(err){
                          console.log(err);
                        }
                      })
                      //保存用户信息
                      wx.cloud.callFunction({
                        name:"setUserInfo",
                        data:{
                          name:that.data.userInfo.nickName
                        },
                        success(res){
                          console.log(res);
                        },
                        fail(err){
                          console.log(err);
                        }
                      })
                    }
                },
                fail(err){
                  console.log(err);
                }
              })

              


            }
          })

         
        }
      }
    })
  },

  onGetUserInfo: function(e) {
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]
        
        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath
            
            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

})
